<template>
    <div
        style="margin-top:20px"
        v-loading="loadingMask"
        :element-loading-text="loadingText"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
    >
        <el-row>
            <el-col :span="24">
                <el-form :model="dataForm" :inline="true" class="demo-ruleForm">
                    <el-form-item label="人员姓名" prop="name">
                        <el-input v-model="dataForm.name" placeholder="请输入人员姓名"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button icon="el-icon-search" type="primary" @click="getList()">查询{{groupIds}}--</el-button>
                        <el-button icon="el-icon-plus" type="primary" @click="add()">新增</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="5">
       
                <h2 class="org-title">组织架构树状图</h2>
                <div class="tree">
                    <span v-if="treeData.length>0">
                    <org-tree
                        @getlist="getList"
                        :treeData="treeData"
                        @showTree="showTree"
                        @lookPersonInfo="lookPersonInfo"
                    />
                </span>
                <span v-else class="no-data">暂无数据</span>
                </div>
            </el-col>
            <div  v-loading="loadingRightMask"
            style="height: 600px"
            :element-loading-text="loadingText"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)">
            <el-col :span="17" style="margin-left:10px" v-if="type=='childEdit'">
                <h2 class="org-title">{{departInfo.name}}>编辑</h2>

                <el-form
                    :model="childDataForm"
                    :rules="rulesChild"
                    ref="ruleChildForm"
                    label-width="120px"
                    class="demo-ruleForm"
                >
                    <el-form-item label="姓名" prop="userName">
                        <el-input v-model="childDataForm.userName"></el-input>
                    </el-form-item>
                    <el-form-item label="职务" prop="duty">
                        <el-input v-model="childDataForm.duty"></el-input>
                    </el-form-item>

                    <el-form-item label="是否是常设部门" prop="leader">
                        <el-radio-group v-model="childDataForm.leader">
                            <el-radio label="true">是</el-radio>
                            <el-radio label="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="submitChildForm('ruleChildForm')">保存</el-button>
                        <el-button type="primary" @click="backPrev('ruleChildForm')">返回</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="17" style="margin-left:10px" v-if="type=='add' || type=='edit'">
                <h2 class="org-title" v-if="addChild">{{departInfo.name}}>新增子部门</h2>
                <h2 class="org-title" v-else>{{type=='add'?'新增':'修改'}}</h2>

                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="120px"
                    class="demo-ruleForm"
                >
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="部门描述" prop="description">
                        <el-input v-model="ruleForm.description"></el-input>
                    </el-form-item>
                    <el-form-item label="上级部门" prop="parentId" v-if="!addChild">
                        <el-select
                            v-model="ruleForm.parentId"
                            placeholder="请选择上级部门"
                            style="width:100%"
                        >
                            <el-option
                                v-for="item in allOrgOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="telephone">
                        <el-input v-model="ruleForm.telephone"></el-input>
                    </el-form-item>
                    <el-form-item label="排序号" prop="sort">
                        <el-input v-model="ruleForm.sort" type="number"></el-input>
                    </el-form-item>

                    <el-form-item label="是否是常设部门" prop="org">
                        <el-radio-group v-model="ruleForm.org">
                            <el-radio label="true">是</el-radio>
                            <el-radio label="false">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="角色" prop="roleIds" v-if="!addChild">
                        <el-select
                            filterable
                            multiple
                            clearable
                            style="width:100%"
                            v-model="ruleForm.roleIds"
                            placeholder="请选择角色"
                        >
                            <el-option
                                v-for="item in roleOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            @click="submitForm('ruleForm')"
                            :loading="loadingBtn"
                        >保存</el-button>
                        <el-button type="primary" @click="backPrev('ruleForm')">返回</el-button>
                    </el-form-item>
                </el-form>
            </el-col>

            <el-col :span="17" style="margin-left:10px" v-if="shopOrgInfo">
                <h2 class="org-title clearfix">
                    <span class="fl">部门介绍</span>
                    <div class="fr btn-box">
                        <el-button type="text" @click="addChildDepat()">新增子部门</el-button>
                        <el-button type="text" @click="editDepat()">修改本部门</el-button>
                        <el-button type="text" @click="delDepat()">删除本部门</el-button>
                    </div>
                </h2>
                <div class="inro">
                    <p>部门名称：{{departInfo.name}}</p>
                    <p>部门描述：{{departInfo.description}}</p>
                    <p>联系电话：{{departInfo.telephone}}</p>
                    <p>是否为常设部门：{{departInfo.org?'是':'否'}}</p>
                </div>
                <h2 class="org-title clearfix">
                    <span class="fl">人员列表</span>
                </h2>
                <div class="select-config" style="margin-bottom:20px">
                    <el-select
                        filterable
                        multiple
                        clearable
                        style="width:70%"
                        class="select-person"
                        v-model="userIds"
                        placeholder="请选择配置人员"
                    >
                        <el-option
                            v-for="item in configOptions"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.userId"
                        ></el-option>
                    </el-select>
                    <el-button
                        @click="confirmConfig()"
                        type="primary"
                        size="small"
                        style="margin-left:20px"
                    >确定</el-button>
                    <el-button
                        @click="delPerson()"
                        type="danger"
                        size="small"
                        icon="el-icon-delete"
                        style="margin-left:20px"
                    >批量删除</el-button>
                </div>
                <div class="person-list">
                    <el-table
                        :data="departInfo.groupUsers"
                        border
                        style="width: 100%"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="userName" label="姓名" align="center" width="100"></el-table-column>

                        <el-table-column prop="duty" label="职务" align="center" width="120"></el-table-column>
                        <el-table-column prop="leader " align="center" label="是否是部门负责人" width="120">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.leader==1">是</el-tag>
                                <el-tag v-if="scope.row.leader==0">否</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" align="center" width="100">
                            <template slot-scope="scope">
                                <el-button
                                    @click="editPerson(scope.row)"
                                    type="text"
                                    size="small"
                                >编辑</el-button>
                                <el-button type="text" size="small" @click="delPerson(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="page">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageNum"
                        :page-sizes="[100, 200, 300, 400]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                    ></el-pagination>
                </div>
            </el-col>
        </div>
        </el-row>
    </div>
</template>
<script>
import API from '../../api/index';
import cloneDeep from 'lodash/cloneDeep';
import { moblleRegex } from '../../utils/validate';
import {mapGetters} from 'vuex'
export default {
    data() {
        var mobile = (rule, value, callback) => {
            moblleRegex(rule, value, callback);
        };
        return {
            treeData: [],
            dataList: [],
            dataForm: {
                name: ''
            },
            type: '',
            shopOrgInfo: true,
            loadingBtn: false,
            loadingMask: false,
            loadingRightMask:false,
            ruleForm: {
                name: '',
                description: '',
                parentId: '',
                telephone: '',
                sort: 0,
                roleIds: [],
                org: 'true'
            },
            childDataForm: {
                duty: '', //职务
                leader: 'true',
                userName: '',
                userId: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                telephone: [{ validator: mobile, trigger: 'change', required: false }]
            },
            rulesChild: {
                userName: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ]
            },
            pageNum: 1,
            pageSize: 10,
            total: 0,
            groupId: '',
            allOrgOptions: [],
            roleOptions: [],
            configOptions: [], // 配置人员信息
            departInfo: {}, //部门信息
            userIds: [], //选择的配置人员信息
            loadingText: '拼命加载中',
            selectDelConfigPerson: [], // 批量删除选择人员
            addChild: false,
         
        };
    },
    computed:{
        ...mapGetters({orgList:'orgList',groupIds:'groupIds'})
    },
    watch: {
        
        orgList(val) {
            console.log(val)
            console.log('发生了为化')
            this.getOrgList();
        this.getAllList();
        this.getRoleList();
        },
        groupIds(val) {
            console.log('监听不到吗')
            console.log('grioddID=>',val)
            this.getList(val)
        },
        userIds(val) {
            if (val.length > 0) {
                document.querySelector('.select-person .el-input__inner').setAttribute('placeholder', '');
            } else {
                document.querySelector('.select-person .el-select__tags span').innerHTML = '';
                document.querySelector('.select-person .el-input__inner').setAttribute('placeholder', '请选择配置人员');
            }
        }
    },
    mounted() {
        console.log(this.$store.state.user.instId)
        if (this.$store.state.user.instId) {
            this.getOrgList();
        this.getAllList();
        this.getRoleList();
        }
       
    },
    methods: {
        // 展开树
        showTree(item){
            console.log(item)
            console.log('展开树')
            var datax = cloneDeep(this.treeData);

function Vnode(data) {
    for (var j in data) {
        if (data[j].groupId == item.groupId) {
            var child = data[j].nextLevelGroups
            for (var k in child) {
                child[k]['tier'] = !child[k]['tier'];
                child[k]['showPic'] = !child[k]['showPic'];
                child[k].show = !child[k].show;
            }
            console.log(data[j])
            data[j]['tier'] = true;
            data[j]['showPic'] = !data[j]['showPic'] ;
            data[j].show = true;
        }
        if (data[j].nextLevelGroups&&data[j].nextLevelGroups.length>0) {
            console.log('下级')
            Vnode(data[j].nextLevelGroups)
        }
    }
    return data
    
}
var resultData = Vnode(datax)
var nodes=[]
console.log('测试')
console.log(resultData)
this.treeData = resultData
        },
        treeDataDeal(val, type) {
            var nodes=[]
            function Vnode(config) {

            }
            if (val.length > 0) {
                for (var k in val) {
                    if (type == 1) {
                        val[k]['show'] = true;
                        val[k]['showPic'] = true;
                        val[k]['tier'] = false;
                    } else {
                        val[k]['show'] = false;
                        val[k]['tier'] = false;
                        val[k]['showPic'] = false;
                    }

                    if (val[k].nextLevelGroups.length > 0) {
                        this.treeDom = val[k].nextLevelGroups;
                        this.treeDataDeal(val[k].nextLevelGroups);
                    }
                }
            }

            this.treeData = val;
        },
        // 查看人员信息
        lookPersonInfo(val) {
            this.loadingMask = true;
            console.log('进入')
            API.role.lookeditConfigPerson({ groupId: val.groupId, userId: val.userId }).then(res => {
           this.type = 'childEdit';
           this.shopOrgInfo = false;
           this.childDataForm = {
               duty: res.data.duty, //职务
                leader: String(res.data.leader),
                userName: res.data.userName,
                userId: res.data.userId
            };
            this.loadingMask = false;
            });
        },
        changeTreeData(val) {
            console.log(val)
            console.log('你要点我吗')
            this.treeData = val
        },
        // 编辑人员列表
        editPerson(row) {
            this.type = 'childEdit';
            this.shopOrgInfo = false;
            this.childDataForm = {
                duty: row.duty, //职务
                leader: String(row.leader),
                userName: row.userName,
                userId: row.userId
            };
        },
        // 新增
        add() {
            this.type = 'add';
            this.shopOrgInfo = false;
            this.addChild = false
            this.ruleForm['parentId'] = ''
        },
        // 新增子部门
        addChildDepat() {
            this.addChild = true;
            this.type = 'add';
            this.shopOrgInfo = false;
            this.ruleForm['parentId'] = this.departInfo.id;
        },
        // 修改本部门
        editDepat() {
            var info = this.departInfo;
            this.type = 'edit';
            this.shopOrgInfo = false;
            var ids = [];
            if (info.groupRoles.length > 0) {
                for (var k in info.groupRoles) {
                    ids.push(info.groupRoles[k].id);
                }
            }
            this.ruleForm = {
                name: info.name,
                description: info.description,
                parentId: info.parentId == 0 ? '' : info.parentId,
                telephone: info.telephone,
                sort: info.sort,
                roleIds: ids,
                org: String(info.org),
                id: info.id
            };
        },
        // 删除本部门
        delDepat() {
            this.$alert('您确定要删除本部门吗?', '', {
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(()=>{
                this.loadingMask = true;
                    API.role.delDepart({ groupId: this.groupId }).then(res => {
                        if (res.code == 20000000) {
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                            });
                            this.type = '';
                            this.shopOrgInfo = true;
                            this.getOrgList();
                        } else {
                            this.$message.error(res.message);
                        }
                        this.loadingMask = false;
                    });
            })
        },
        handleSelectionChange(val) {
            this.selectDelConfigPerson = val;
        },

        // 删除选中的人
        delPerson(row) {
            var ids = [];
            var selectArry = this.selectDelConfigPerson;
            if (row) {
                ids = [row.userId];
            } else {
                if (selectArry.length > 0) {
                    for (var k in selectArry) {
                        ids.push(selectArry[k].userId);
                    }
                } else {
                    this.$message.error('请先选择勾选项');
                    return;
                }
            }
            this.$alert('您确定要删除吗?', '', {
                confirmButtonText: '确定',
                callback: action => {
                    this.loadingMask = true;
                    API.role.delConfigPerson({ groupId: this.groupId, ids: ids }).then(res => {
                        if (res.code == 20000000) {
                            this.$message({
                                type: 'success',
                                message: '删除成功'
                            });
                            this.getOrgList();
                        } else {
                            this.$message.error(res.message);
                        }
                        this.loadingMask = false;
                    });
                }
            });
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pageNum = val;
            this.getList();
        },
        // 选择配置人员信息
        confirmConfig() {
            var userIds = this.userIds;
            console.log(userIds)
            if (userIds.length==0) {
                this.$message.error('请选择配置人员')
                return
            }
            var configOptions = this.configOptions;
            var data = [];
            for (var k in userIds) {
                for (var y in configOptions) {
                    if (userIds[k] == configOptions[y].userId) {
                        data.push({ userId: configOptions[y].userId, userName: configOptions[y].userName, groupId: this.groupId });
                    }
                }
            }
            this.loadingMask = true;
            API.role.configPersonInfo({ data, groupId: this.groupId }).then(res => {
                if (res.code == 20000000) {
                    this.$message({
                        type: 'success',
                        message: '添加成功'
                    });
                    this.type = '';
                    this.shopOrgInfo = true;
                    this.configOptions = [];
                    this.userIds = [];
                    document.querySelector('.select-person .el-select__tags span').innerHTML = '';
                    document.querySelector('.select-person .el-input__inner').setAttribute('placeholder', '请选择配置人员');
                    this.getOrgList();
                } else {
                    this.$message.error(res.message);
                }
                this.loadingMask = false;
            });
        },
        // 获取配置人员信息
        getConfigPerson() {
            var data = {
                instId: this.$store.state.user.instId
            };
            API.role.getConfigPersonList(data).then(res => {
                if (res.code == 20000000 && res.data.length > 0) {
                    var data = res.data;
                    var selectConfig = this.dataList;
                    var newList = [];
                    for (var k in selectConfig) {
                        for (var y in data) {
                            if (selectConfig[k].userId == data[y].userId) {
                                data.splice(y, 1);
                            }
                        }
                    }
                    this.configOptions = data;
                }
            });
        },
        lookDepatInfo(row) {
            this.getList(row.groupId);
        },

        // 获取人员列表及部门信息
        getList(id) {
            var data = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                groupId: id || this.groupId,
                userName: this.dataForm.name
            };
             this.loadingMask = true;
            API.role.getPersonList(data).then(res => {
                if (res.code == 20000000) {
                   this.type = '';
                   this.shopOrgInfo = true;
                   console.log('获取部门信息')
                    this.departInfo = res.data;
                   this.dataList = res.data.groupUsers;
                   this.getConfigPerson();
                }
                 this.loadingMask = false
            });
        },
        // 组织架构列表
        getOrgList() {
            var params = {};
            this.treeData = []
            params['instId'] = this.$store.state.user.instId;
            params['instSub'] = this.$store.state.user.instSub;
            this.loadingMask = true;
            console.log('组吸引人001')

            API.role.getOrgFrameWorkList(params).then(res => {
                console.log('获取组织架构')
                console.log(res)
                if (res.code == 20000000 && res.data.length > 0) {
                    console.log('获取组织架构000')
                    var data = res.data;
                
                    this.groupId = res.data[0].groupId;
                    this.treeDataDeal(data, 1);
                    this.getList();
                } else {
                    this.treeData = []
                }
                this.loadingMask = false;
            });
        },
        // 获取角色列表
        getRoleList() {
            let params = {};
            params.pageNum = this.pageNum;
            params.pageSize = 1000;
            params['instId'] = this.$store.state.user.instId;
            params['instSub'] = this.$store.state.user.instSub;
            this.loadingMask = true;
            API.role.getorgRoleList(params).then(res => {
                this.loadingMask = false;
                if (res.code == 20000000) {
                    this.roleOptions = res.data.rows;
                }
            });
        },
        // 获取所有组织架构列表
        getAllList() {
            var params = {};
            params['instId'] = this.$store.state.user.instId;
            params['instSub'] = this.$store.state.user.instSub;
            API.role.getOrgFrameWorkAllList(params).then(res => {
                if (res.code == 20000000) {
                    this.allOrgOptions = res.data;
                }
            });
        },
        backPrev() {
            this.type = '';
            this.shopOrgInfo = true;
        },
        submitForm(formName) {
            this.loadingBtn = true;
            this.$refs[formName].validate(valid => {
                if (valid) {
                    var params = cloneDeep(this.ruleForm);
                    params['instId'] = this.$store.state.user.instId;
                    params['instSub'] = this.$store.state.user.instSub;
                    if (params['parentId'] == '') {
                        params['parentId'] = '0';
                    }
                    if (this.type == 'add') {
                        API.role.addDepart(params).then(res => {
                            if (res.code == 20000000) {
                                this.$message({
                                    type: 'success',
                                    message: '新增成功'
                                });
                                this.getOrgList();
                                this.getAllList();
                                this.type = '';
                                this.shopOrgInfo = true;
                            } else {
                                this.$message.error(res.message);
                            }
                            this.loadingBtn = false;
                        });
                    } else {
                        API.role.editDepart(params).then(res => {
                            if (res.code == 20000000) {
                                this.$message({
                                    type: 'success',
                                    message: '编辑成功'
                                });
                                this.getOrgList();
                                this.getAllList();
                                this.type = '';
                                this.shopOrgInfo = true;
                            } else {
                                this.$message.error(res.message);
                            }
                            this.loadingBtn = false;
                        });
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        submitChildForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    var params = cloneDeep(this.childDataForm);

                    this.loadingMask = true;
                    API.role.editConfigPerson({ data: params, groupId: this.groupId }).then(res => {
                        if (res.code == 20000000) {
                            this.$message({
                                type: 'success',
                                message: '编辑成功'
                            });
                            this.getOrgList();
                            this.getAllList();
                            this.type = '';
                            this.shopOrgInfo = true;
                        } else {
                            this.$message.error(res.message);
                        }
                        this.loadingMask = false;
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
};
</script>
<style scoped>
.org-title {
    color: #909399;
    margin-bottom: 20px;
    font-size: 12px;
    background: #ebebeb;
    height: 38px;
    line-height: 38px;
    padding-left: 10px;
    padding-right: 10px;
}
.tree .no-data {
    text-align: center;
    display: block;
    font-size: 14px;
    color: #ccc;
    margin-top:40px;
}
.inro {
    padding-left: 10px;
}
.inro p {
    line-height: 140%;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;
}
.tree li img.person {
    width: 15px;
    height: 17px;
}
</style>